package com.ycb.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author 黄泽群
 * @since 2024-01-02
 */
@Slf4j
public class ReentrantLockApp {

    static ReentrantLock reentrantLock = new ReentrantLock();

    public static void main(String[] args) {
//        ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
        log.info("x");
        for (int i = 0; i < 2; i++) {
            newRunnable().start();
        }
    }

    public static Thread newRunnable(){
        final int num = 10;
        return new Thread(){
            @Override
            public void run() {
                for (int i = 1; i <= num; i++) {
                    try {
                        reentrantLock.lock();
                        log.info(" lock begin num:{}",i);
                        TimeUnit.SECONDS.sleep(1L);
                        log.info(" lock end num:{}",i);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }finally {
                        reentrantLock.unlock();
                    }
                }
            }
        };
    }
}
